require ('./common.js');
require ('./config.js');
var sc = require ('./screenshot.js');
var scs = require ('./camera.js');

var mqtt = require('mqtt');

var qttstr = {}; //定义消息（可以为字符串，对象等）
qttstr.machineid = global.machine_id; 
qttstr.state = 0; 
qttstr.playerid = global.playerid;

var options = {
	//mqtt客户端的id，这里面应该还可以加上其他参数，具体看官方文档
	clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
	//username:'admin',
	//password:'112233',
	will: {
		topic: 'super/machine/offline',
		payload: JSON.stringify(qttstr),
		qos: 0,
		retain: false
	}      
}    

global.MqttClient = mqtt.connect(global.mqtt_center_server,options) // you add a ws:// url here

global.MqttClient.on('connect', function () {
    console.log("中心服务器连接成功!")

    var qttstr = {}; //定义消息（可以为字符串，对象等）
    qttstr.machineid = global.machine_id; 
    qttstr.state = 1;  
    qttstr.playerid = global.playerid;

    global.MqttClient.publish('super/machine/goline',JSON.stringify(qttstr),{ qos: 0, retain: false })

    var subscribes = ['super/machine/videoadvertising',
                      'super/machine/websiterefresh',
                      'super/machine/serialport',
                      'super/machine/camera',
                      'super/machine/screenshot',
                      'super/machine/advertfullscreen',
                      'super/machine/refreshscreen',
                      'super/machine/releaseadvert'];
    //订阅主题 presence
    global.MqttClient.subscribe(subscribes, function (err) {
      if (!err) {
        console.log("中心服务器消息订阅成功!")
      }else{
      //打印错误
        console.log(err)
      }
    })

    subscribes = ['super/machine/shipment/'+global.machine_id];   
       
    global.MqttClient.subscribe(subscribes, {qos:2},function (err) {
      if (!err) {
        console.log("中心服务器qos2消息订阅成功!")
      }else{
      //打印错误
        console.log(err)
      }
    })  
});

//如果连接错误，打印错误
global.MqttClient.on('error', function (err) {
	console.log(err)
	global.MqttClient.end()
});

global.MqttClient.on('message', function (topic, message) {
  // message is Buffer
  var msg = message.toString();
  var topicstr = topic.toString();

  console.log("订阅消息" + topic + ":" + msg);

  try{ 
    if(topicstr == 'super/machine/videoadvertising') {
      var params = JSON.parse( msg );

      if(params.machineid == -1 || params.machineid == global.machine_id) {
        var qttstr = {}; //定义消息（可以为字符串，对象等）
        qttstr.vaaddress = params.vaaddress;    

        global.MqttServer.publish({ topic: topicstr, payload: JSON.stringify(qttstr) });
      }
    }
    else if(topicstr == 'super/machine/websiterefresh' ||
            topicstr == 'super/machine/advertfullscreen' ||
            topicstr == 'super/machine/refreshscreen' ||
            topicstr == 'super/machine/releaseadvert') {
      var params = JSON.parse( msg );

      if(params.machineid == -1 || params.machineid == global.machine_id) {
        global.MqttServer.publish({ topic: topicstr,payload:msg});
      }
    }
    else if(topicstr == 'super/machine/serialport') {

    }  
    else if(topicstr == 'super/machine/camera') {
        var params = JSON.parse( msg );

        if(params.machineid == global.machine_id) {
          scs(params.playerid);
        }
    }  
    else if(topicstr == 'super/machine/screenshot') {
        var params = JSON.parse( msg );

        if(params.machineid == global.machine_id) {    
          sc(params.playerid);
        }
    } 
    else if(topicstr == 'super/machine/shipment') {
        var params = JSON.parse( msg );

        if(params.machine_id == global.machine_id &&
           params.playerid == global.playerid &&
           params.paymentcode == global.paymentcode) {    
          // 转到机器开始出货
          console.log('机器'+params.machine_id+'开始出货.');

        }
        else {
          var qttstr = {}; //定义消息（可以为字符串，对象等）
          qttstr.machine_id = params.machine_id;  
          qttstr.playerid = params.playerid;   
          qttstr.cargoway = params.cargoway;   
          qttstr.paymentcode = params.paymentcode;   
          qttstr.orderid = params.orderid;            
          qttstr.state = 1;  

          global.MqttClient.publish('super/machine/shipment/return',JSON.stringify(qttstr),{qos:2});

          console.log('机器'+params.machine_id+'出货失败.');
        }
    } 
   }catch(exception){
    console.info(exception.message);
   }        
});

function callbackFun(){
  console.log('22222')
}


